package com.accounting.ui;

import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.control.*;
import javafx.scene.chart.*;
import javafx.geometry.Insets;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.time.LocalDate;
import com.accounting.db.DatabaseManager;
import java.sql.*;

public class ReportView {
    private VBox root;
    private DatePicker startDate;
    private DatePicker endDate;
    private ComboBox<String> reportType;
    private VBox chartContainer;

    public ReportView() {
        createContent();
    }

    private void createContent() {
        root = new VBox(20);
        root.setPadding(new Insets(20));

        // 创建筛选条件区域
        HBox filterBox = new HBox(10);
        Label dateLabel = new Label("日期范围：");
        startDate = new DatePicker(LocalDate.now().minusMonths(1));
        endDate = new DatePicker(LocalDate.now());
        
        reportType = new ComboBox<>();
        reportType.getItems().addAll("收支分类饼图", "每日收支趋势", "收支分类柱状图");
        reportType.setValue("收支分类饼图");
        
        Button generateBtn = new Button("生成报表");
        generateBtn.setOnAction(e -> generateReport());

        filterBox.getChildren().addAll(dateLabel, startDate, new Label("至"), 
                                     endDate, reportType, generateBtn);

        // 创建图表容器
        chartContainer = new VBox();
        chartContainer.setMinHeight(400);

        root.getChildren().addAll(filterBox, chartContainer);
    }

    private void generateReport() {
        chartContainer.getChildren().clear();
        String selectedType = reportType.getValue();
        
        switch (selectedType) {
            case "收支分类饼图" -> generatePieChart();
            case "每日收支趋势" -> generateLineChart();
            case "收支分类柱状图" -> generateBarChart();
        }
    }

    private void generatePieChart() {
        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT category, SUM(amount) as total 
                FROM transactions 
                WHERE date BETWEEN ? AND ?
                GROUP BY category
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, startDate.getValue().toString());
            pstmt.setString(2, endDate.getValue().toString());
            
            ResultSet rs = pstmt.executeQuery();
            
            ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList();
            while (rs.next()) {
                pieChartData.add(new PieChart.Data(
                    rs.getString("category"), 
                    rs.getDouble("total")
                ));
            }
            
            PieChart chart = new PieChart(pieChartData);
            chart.setTitle("收支分类统计");
            chartContainer.getChildren().add(chart);
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void generateLineChart() {
        NumberAxis yAxis = new NumberAxis();
        CategoryAxis xAxis = new CategoryAxis();
        
        LineChart<String, Number> lineChart = 
            new LineChart<>(xAxis, yAxis);
        
        lineChart.setTitle("收支趋势");
        xAxis.setLabel("日期");
        yAxis.setLabel("金额");

        XYChart.Series<String, Number> incomeSeries = new XYChart.Series<>();
        incomeSeries.setName("收入");
        
        XYChart.Series<String, Number> expenseSeries = new XYChart.Series<>();
        expenseSeries.setName("支出");

        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT 
                    strftime('%Y-%m', date) as month,
                    type,
                    SUM(amount) as total
                FROM transactions 
                WHERE date BETWEEN ? AND ?
                GROUP BY month, type
                ORDER BY month
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, startDate.getValue().toString());
            pstmt.setString(2, endDate.getValue().toString());
            
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                String month = rs.getString("month");
                double amount = rs.getDouble("total");
                String type = rs.getString("type");
                
                if ("收入".equals(type)) {
                    incomeSeries.getData().add(new XYChart.Data<>(month, amount));
                } else {
                    expenseSeries.getData().add(new XYChart.Data<>(month, amount));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        lineChart.getData().addAll(incomeSeries, expenseSeries);
        chartContainer.getChildren().add(lineChart);
    }

    private void generateBarChart() {
        CategoryAxis xAxis = new CategoryAxis();
        NumberAxis yAxis = new NumberAxis();
        
        BarChart<String, Number> barChart = 
            new BarChart<>(xAxis, yAxis);
        
        barChart.setTitle("收支分类统计");
        xAxis.setLabel("分类");
        yAxis.setLabel("金额");

        XYChart.Series<String, Number> series = new XYChart.Series<>();
        series.setName("金额");

        try (Connection conn = DatabaseManager.getConnection()) {
            String sql = """
                SELECT category, SUM(amount) as total 
                FROM transactions 
                WHERE date BETWEEN ? AND ? 
                GROUP BY category
            """;
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, startDate.getValue().toString());
            pstmt.setString(2, endDate.getValue().toString());
            
            ResultSet rs = pstmt.executeQuery();
            
            while (rs.next()) {
                series.getData().add(new XYChart.Data<>(
                    rs.getString("category"),
                    rs.getDouble("total")
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        barChart.getData().add(series);
        chartContainer.getChildren().add(barChart);
    }

    public VBox getView() {
        return root;
    }
} 